package com.cosmo.spi.demo1;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import com.alibaba.fastjson.JSON;

import java.sql.Connection;

public class CosmoTest {
    SimpleDateFormat sdf;
    String url;
    String username;
    String password;

    public CosmoTest() {
        this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.url = "jdbc:mysql://192.168.0.138:3306/cosmotest?useUnicode=true&characterEncoding=utf-8&";
        this.username = "cosmo_test";
        this.password = "ULV8$BmRti";
    }

    private String resultBack(boolean flag) {
        if (flag) {
            return "{\"code\": 1,\"info\": \"成功\", \"data\":\"\"}";
        }
        return "{\"code\": 0,\"info\": \"失败\", \"data\":\"\"}";
    }


    public static void main(String[] args) {
        CosmoTest cosmoTest = new CosmoTest();
        try {
            cosmoTest.fourTypesTest(11, "acb", new Tst("", "小小五"), new String[]{"小武"});
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public String fourTypesTest(int aa, String abc, Tst tst, String[] strArr) throws SQLException, ClassNotFoundException {
        StringBuilder sb = new StringBuilder("INSERT INTO `testlyw`(`aaa`, `bbb`, `ccc`, `dddd`) VALUES (");
        sb.append("'").append(JSON.toJSONString(Integer.valueOf(aa))).append("'").append(",")
                .append("'")
                .append(JSON.toJSONString(abc)).append("'").append(",")
                .append("'")
                .append(JSON.toJSONString(tst)).append("'").append(",")
                .append("'")
                .append(JSON.toJSONString(strArr)).append("'").append(")");
        try {
            sqlSave(sb.toString());
            return resultBack(true);
        } catch (Exception e) {
            e.printStackTrace();
            return resultBack(false);
        }
    }

    private void sqlSave(String sql) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver", true, Thread.currentThread().getContextClassLoader());
            conn = DriverManager.getConnection(this.url, this.username, this.password);

            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
